#include "salesanalysis.h"
#include "../dao/salesanalysisdao.h"
#include "../database/database.h"
#include "../appinitializer.h"
#include <QApplication>
#include <QMessageBox>
#include <QDebug>
#include <QDateTime>
#include <QTimer>

// 销售分析窗口类，用于展示各类销售数据图表（柱状图、饼图等）
SalesAnalysis::SalesAnalysis(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_toolbarLayout(nullptr)
    , m_stackedWidget(nullptr)
    , m_chartBtn(nullptr)
    , m_categoryBtn(nullptr)
    , m_staffBtn(nullptr)
    , m_paymentBtn(nullptr)
    , m_refreshBtn(nullptr)
    , m_startDateEdit(nullptr)
    , m_endDateEdit(nullptr)
    , m_chartAnalysisWidget(nullptr)
    , m_chartView(nullptr)
    , m_chart(nullptr)
    , m_barSeries(nullptr)
    , m_salesAmountSet(nullptr)
    , m_grossProfitSet(nullptr)
    , m_axisX(nullptr)
    , m_axisY(nullptr)
    , m_timeToggleBtn(nullptr)
    , m_salesAmountToggleBtn(nullptr)
    , m_grossProfitToggleBtn(nullptr)
    , m_categoryAnalysisWidget(nullptr)
    , m_categoryChartView(nullptr)
    , m_categoryChart(nullptr)
    , m_categorySeries(nullptr)
    , m_staffAnalysisWidget(nullptr)
    , m_staffChartView(nullptr)
    , m_staffChart(nullptr)
    , m_staffSeries(nullptr)
    , m_paymentAnalysisWidget(nullptr)
    , m_paymentChartView(nullptr)
    , m_paymentChart(nullptr)
    , m_paymentSeries(nullptr)
    , m_salesAnalysisDAO(nullptr)
    , m_isMonthlyView(true)
    , m_showSalesAmount(true)
    , m_showGrossProfit(true)
{
    // 初始化数据访问层，通过应用初始化器获取数据库连接
    Database *db = AppInitializer::database();
    m_salesAnalysisDAO = new SalesAnalysisDAO(db, this);

    initUI();
    setupStyles();

    // 默认显示图表分析视图
    showChartAnalysis();

    // 延迟100ms加载初始数据，避免UI阻塞
    QTimer::singleShot(100, this, &SalesAnalysis::refreshData);
}

SalesAnalysis::~SalesAnalysis()
{
}

// 初始化UI组件及布局结构
void SalesAnalysis::initUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(20, 20, 20, 20);
    m_mainLayout->setSpacing(15);

    createToolbar();

    // 堆栈窗口用于切换不同分析视图
    m_stackedWidget = new QStackedWidget(this);
    m_mainLayout->addWidget(m_stackedWidget);

    // 创建各类分析视图
    createChartAnalysisView();
    createCategoryAnalysisView();
    createStaffAnalysisView();
    createPaymentAnalysisView();
}

// 创建工具栏，包含视图切换按钮、日期选择器和刷新按钮
void SalesAnalysis::createToolbar()
{
    m_toolbarLayout = new QHBoxLayout();
    m_toolbarLayout->setSpacing(10);

    // 视图切换按钮（可勾选）
    m_chartBtn = new QPushButton(tr("销售图表"), this);
    m_categoryBtn = new QPushButton(tr("分类统计"), this);
    m_staffBtn = new QPushButton(tr("导购统计"), this);
    m_paymentBtn = new QPushButton(tr("支付统计"), this);

    m_chartBtn->setCheckable(true);
    m_categoryBtn->setCheckable(true);
    m_staffBtn->setCheckable(true);
    m_paymentBtn->setCheckable(true);

    // 日期选择器，默认显示近30天数据
    m_startDateEdit = new QDateEdit(this);
    m_endDateEdit = new QDateEdit(this);
    m_startDateEdit->setDate(QDate::currentDate().addDays(-30));
    m_endDateEdit->setDate(QDate::currentDate());
    m_startDateEdit->setCalendarPopup(true);
    m_endDateEdit->setCalendarPopup(true);

    m_refreshBtn = new QPushButton(tr("刷新数据"), this);

    // 布局添加组件
    m_toolbarLayout->addWidget(m_chartBtn);
    m_toolbarLayout->addWidget(m_categoryBtn);
    m_toolbarLayout->addWidget(m_staffBtn);
    m_toolbarLayout->addWidget(m_paymentBtn);
    m_toolbarLayout->addStretch();
    m_toolbarLayout->addWidget(new QLabel(tr("开始日期:"), this));
    m_toolbarLayout->addWidget(m_startDateEdit);
    m_toolbarLayout->addWidget(new QLabel(tr("结束日期:"), this));
    m_toolbarLayout->addWidget(m_endDateEdit);
    m_toolbarLayout->addWidget(m_refreshBtn);

    m_mainLayout->addLayout(m_toolbarLayout);

    // 连接按钮信号与对应槽函数
    connect(m_chartBtn, &QPushButton::clicked, this, &SalesAnalysis::showChartAnalysis);
    connect(m_categoryBtn, &QPushButton::clicked, this, &SalesAnalysis::showCategoryAnalysis);
    connect(m_staffBtn, &QPushButton::clicked, this, &SalesAnalysis::showStaffAnalysis);
    connect(m_paymentBtn, &QPushButton::clicked, this, &SalesAnalysis::showPaymentAnalysis);
    connect(m_refreshBtn, &QPushButton::clicked, this, &SalesAnalysis::refreshData);
}

// 创建销售图表分析视图（柱状图）
void SalesAnalysis::createChartAnalysisView()
{
    m_chartAnalysisWidget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(m_chartAnalysisWidget);
    layout->setContentsMargins(10, 10, 10, 10);

    // 图表控制按钮布局（时间视图切换、数据项显示切换）
    QHBoxLayout *controlLayout = new QHBoxLayout();
    m_timeToggleBtn = new QPushButton(tr("切换到日视图"), this);
    m_salesAmountToggleBtn = new QPushButton(tr("隐藏销售额"), this);
    m_grossProfitToggleBtn = new QPushButton(tr("隐藏毛利润"), this);

    m_timeToggleBtn->setCheckable(true);
    m_salesAmountToggleBtn->setCheckable(true);
    m_grossProfitToggleBtn->setCheckable(true);

    controlLayout->addWidget(m_timeToggleBtn);
    controlLayout->addWidget(m_salesAmountToggleBtn);
    controlLayout->addWidget(m_grossProfitToggleBtn);
    controlLayout->addStretch();

    layout->addLayout(controlLayout);

    // 初始化图表组件
    m_chart = new QChart();
    m_chart->setTitle(tr("销售数据分析"));
    m_chart->setAnimationOptions(QChart::SeriesAnimations);

    m_barSeries = new QBarSeries();
    m_salesAmountSet = new QBarSet(tr("销售额"));
    m_grossProfitSet = new QBarSet(tr("毛利润"));

    // 添加数据系列到图表
    if (m_showSalesAmount) {
        m_barSeries->append(m_salesAmountSet);
    }
    if (m_showGrossProfit) {
        m_barSeries->append(m_grossProfitSet);
    }
    m_chart->addSeries(m_barSeries);

    // 初始化坐标轴
    m_axisX = new QBarCategoryAxis();
    m_axisY = new QValueAxis();
    m_axisY->setTitleText(tr("金额 (元)"));

    m_chart->addAxis(m_axisX, Qt::AlignBottom);
    m_chart->addAxis(m_axisY, Qt::AlignLeft);
    m_barSeries->attachAxis(m_axisX);
    m_barSeries->attachAxis(m_axisY);

    // 创建图表视图并启用抗锯齿
    m_chartView = new QChartView(m_chart);
    m_chartView->setRenderHint(QPainter::Antialiasing);
    m_chart->setAcceptHoverEvents(true);
    layout->addWidget(m_chartView);

    m_stackedWidget->addWidget(m_chartAnalysisWidget);

    // 连接控制按钮信号
    connect(m_timeToggleBtn, &QPushButton::clicked, this, &SalesAnalysis::toggleTimeView);
    connect(m_salesAmountToggleBtn, &QPushButton::clicked, this, &SalesAnalysis::toggleSalesAmount);
    connect(m_grossProfitToggleBtn, &QPushButton::clicked, this, &SalesAnalysis::toggleGrossProfit);
}

// 创建分类销售统计视图（饼图）
void SalesAnalysis::createCategoryAnalysisView()
{
    m_categoryAnalysisWidget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(m_categoryAnalysisWidget);
    layout->setContentsMargins(10, 10, 10, 10);

    QLabel *titleLabel = new QLabel(tr("销售分类统计"), this);
    titleLabel->setAlignment(Qt::AlignCenter);
    layout->addWidget(titleLabel);

    // 初始化饼图组件
    m_categoryChart = new QChart();
    m_categoryChart->setTitle(tr("各分类销售占比"));
    m_categoryChart->setAnimationOptions(QChart::SeriesAnimations);

    m_categorySeries = new QPieSeries();
    m_categoryChart->addSeries(m_categorySeries);

    m_categoryChartView = new QChartView(m_categoryChart);
    m_categoryChartView->setRenderHint(QPainter::Antialiasing);
    m_categoryChart->setAcceptHoverEvents(true);
    layout->addWidget(m_categoryChartView);

    m_stackedWidget->addWidget(m_categoryAnalysisWidget);

    // 连接饼图切片点击事件
    connect(m_categorySeries, &QPieSeries::clicked, this, &SalesAnalysis::onPieSliceClicked);
}

// 创建导购销售统计视图（饼图）
void SalesAnalysis::createStaffAnalysisView()
{
    m_staffAnalysisWidget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(m_staffAnalysisWidget);
    layout->setContentsMargins(10, 10, 10, 10);

    QLabel *titleLabel = new QLabel(tr("导购销售统计"), this);
    titleLabel->setAlignment(Qt::AlignCenter);
    layout->addWidget(titleLabel);

    // 初始化饼图组件
    m_staffChart = new QChart();
    m_staffChart->setTitle(tr("各导购销售占比"));
    m_staffChart->setAnimationOptions(QChart::SeriesAnimations);

    m_staffSeries = new QPieSeries();
    m_staffChart->addSeries(m_staffSeries);

    m_staffChartView = new QChartView(m_staffChart);
    m_staffChartView->setRenderHint(QPainter::Antialiasing);
    m_staffChart->setAcceptHoverEvents(true);
    layout->addWidget(m_staffChartView);

    m_stackedWidget->addWidget(m_staffAnalysisWidget);

    connect(m_staffSeries, &QPieSeries::clicked, this, &SalesAnalysis::onPieSliceClicked);
}

// 创建支付方式统计视图（饼图）
void SalesAnalysis::createPaymentAnalysisView()
{
    m_paymentAnalysisWidget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(m_paymentAnalysisWidget);
    layout->setContentsMargins(10, 10, 10, 10);

    QLabel *titleLabel = new QLabel(tr("支付方式统计"), this);
    titleLabel->setAlignment(Qt::AlignCenter);
    layout->addWidget(titleLabel);

    // 初始化饼图组件
    m_paymentChart = new QChart();
    m_paymentChart->setTitle(tr("各支付方式占比"));
    m_paymentChart->setAnimationOptions(QChart::SeriesAnimations);

    m_paymentSeries = new QPieSeries();
    m_paymentChart->addSeries(m_paymentSeries);

    m_paymentChartView = new QChartView(m_paymentChart);
    m_paymentChartView->setRenderHint(QPainter::Antialiasing);
    m_paymentChart->setAcceptHoverEvents(true);
    layout->addWidget(m_paymentChartView);

    m_stackedWidget->addWidget(m_paymentAnalysisWidget);

    connect(m_paymentSeries, &QPieSeries::clicked, this, &SalesAnalysis::onPieSliceClicked);
}

// 设置UI组件样式
void SalesAnalysis::setupStyles()
{
    setStyleSheet(
        "QWidget {"
        "    background-color: #f5f5f5;"
        "    font-family: 'Microsoft YaHei';"
        "}"
        "QPushButton {"
        "    background-color: #4CAF50;"
        "    color: white;"
        "    border: none;"
        "    padding: 8px 16px;"
        "    border-radius: 4px;"
        "    font-size: 14px;"
        "    font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "    background-color: #45a049;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #3d8b40;"
        "}"
        "QPushButton:checked {"
        "    background-color: #2E7D32;"
        "}"
        "QDateEdit {"
        "    background-color: white;"
        "    border: 2px solid #ddd;"
        "    border-radius: 4px;"
        "    padding: 5px;"
        "    font-size: 14px;"
        "}"
        "QLabel {"
        "    color: #333;"
        "    font-size: 14px;"
        "}"
    );

    if (m_chart) {
        m_chart->setBackgroundBrush(QBrush(QColor(245, 245, 245)));
        m_chart->setTitleBrush(QBrush(QColor(51, 51, 51)));
    }
}

// 显示销售图表分析视图
void SalesAnalysis::showChartAnalysis()
{
    m_chartBtn->setChecked(true);
    m_categoryBtn->setChecked(false);
    m_staffBtn->setChecked(false);
    m_paymentBtn->setChecked(false);

    m_stackedWidget->setCurrentWidget(m_chartAnalysisWidget);
    loadChartData();
}

// 显示分类统计视图
void SalesAnalysis::showCategoryAnalysis()
{
    m_chartBtn->setChecked(false);
    m_categoryBtn->setChecked(true);
    m_staffBtn->setChecked(false);
    m_paymentBtn->setChecked(false);

    m_stackedWidget->setCurrentWidget(m_categoryAnalysisWidget);
    loadCategoryData();
}

// 显示导购统计视图
void SalesAnalysis::showStaffAnalysis()
{
    m_chartBtn->setChecked(false);
    m_categoryBtn->setChecked(false);
    m_staffBtn->setChecked(true);
    m_paymentBtn->setChecked(false);

    m_stackedWidget->setCurrentWidget(m_staffAnalysisWidget);
    loadStaffData();
}

// 显示支付统计视图
void SalesAnalysis::showPaymentAnalysis()
{
    m_chartBtn->setChecked(false);
    m_categoryBtn->setChecked(false);
    m_staffBtn->setChecked(false);
    m_paymentBtn->setChecked(true);

    m_stackedWidget->setCurrentWidget(m_paymentAnalysisWidget);
    loadPaymentData();
}

// 切换时间视图（月/日）
void SalesAnalysis::toggleTimeView()
{
    m_isMonthlyView = !m_isMonthlyView;
    m_timeToggleBtn->setText(m_isMonthlyView ? tr("切换到日视图") : tr("切换到月视图"));
    loadChartData();
}

// 切换销售额显示状态（预留接口）
void SalesAnalysis::toggleSalesAmount()
{
    qDebug() << "toggleSalesAmount: 按钮被点击，但功能已禁用";
}

// 切换毛利润显示状态（预留接口）
void SalesAnalysis::toggleGrossProfit()
{
    qDebug() << "toggleGrossProfit: 按钮被点击，但功能已禁用";
}

// 刷新当前视图数据
void SalesAnalysis::refreshData()
{
    if (!m_stackedWidget) return;

    // 根据当前显示的视图刷新对应数据
    if (m_stackedWidget->currentWidget() == m_chartAnalysisWidget) {
        loadChartData();
    } else if (m_stackedWidget->currentWidget() == m_categoryAnalysisWidget) {
        loadCategoryData();
    } else if (m_stackedWidget->currentWidget() == m_staffAnalysisWidget) {
        loadStaffData();
    } else if (m_stackedWidget->currentWidget() == m_paymentAnalysisWidget) {
        loadPaymentData();
    }
}

// 饼图切片点击事件处理（显示详情并切换突出状态）
void SalesAnalysis::onPieSliceClicked()
{
    QPieSlice *slice = qobject_cast<QPieSlice*>(sender());
    if (slice) {
        slice->setExploded(!slice->isExploded());

        QString message = QString(tr("分类: %1\n金额: %2 元\n占比: %3%"))
                         .arg(slice->label())
                         .arg(slice->value(), 0, 'f', 2)
                         .arg(slice->percentage() * 100, 0, 'f', 1);

        QMessageBox::information(this, tr("详细信息"), message);
    }
}

// 加载销售图表数据（柱状图）
void SalesAnalysis::loadChartData()
{
    if (!m_salesAnalysisDAO || !m_startDateEdit || !m_endDateEdit) {
        qDebug() << "loadChartData: 必要组件未初始化";
        return;
    }

    QDate startDate = m_startDateEdit->date();
    QDate endDate = m_endDateEdit->date();

    qDebug() << "loadChartData: 开始查询数据，日期范围:" << startDate << "到" << endDate;

    // 设置10秒查询超时
    QTimer *timeoutTimer = new QTimer(this);
    timeoutTimer->setSingleShot(true);
    timeoutTimer->setInterval(10000);

    bool *queryCompleted = new bool(false);

    // 超时处理
    connect(timeoutTimer, &QTimer::timeout, this, [this, queryCompleted, timeoutTimer]() {
        if (!*queryCompleted) {
            qDebug() << "loadChartData: 查询超时，使用空数据";
            m_chartData.clear();
            updateBarChart();
        }
        delete queryCompleted;
        timeoutTimer->deleteLater();
    });

    timeoutTimer->start();

    // 异步执行数据库查询，避免阻塞UI
    QTimer::singleShot(0, this, [this, startDate, endDate, queryCompleted, timeoutTimer]() {
        try {
            m_chartData = m_salesAnalysisDAO->getSalesChartData(startDate, endDate, m_isMonthlyView);
            qDebug() << "loadChartData: 查询完成，数据条数:" << m_chartData.size();

            *queryCompleted = true;
            timeoutTimer->stop();

            // 主线程更新UI
            QTimer::singleShot(0, this, [this]() {
                updateBarChart();
            });
        } catch (const std::exception& e) {
            qDebug() << "loadChartData: 数据库查询异常:" << e.what();
            m_chartData.clear();

            *queryCompleted = true;
            timeoutTimer->stop();

            QTimer::singleShot(0, this, [this]() {
                updateBarChart();
            });
        } catch (...) {
            qDebug() << "loadChartData: 未知异常";
            m_chartData.clear();

            *queryCompleted = true;
            timeoutTimer->stop();

            QTimer::singleShot(0, this, [this]() {
                updateBarChart();
            });
        }
    });
}

// 加载分类销售数据（饼图）
void SalesAnalysis::loadCategoryData()
{
    if (!m_salesAnalysisDAO) return;

    QDate startDate = m_startDateEdit->date();
    QDate endDate = m_endDateEdit->date();

    m_categoryData = m_salesAnalysisDAO->getCategorySalesData(startDate, endDate);
    updateCategoryPieChart();
}

// 加载导购销售数据（饼图）
void SalesAnalysis::loadStaffData()
{
    if (!m_salesAnalysisDAO) return;

    QDate startDate = m_startDateEdit->date();
    QDate endDate = m_endDateEdit->date();

    m_staffData = m_salesAnalysisDAO->getStaffSalesData(startDate, endDate);
    updateStaffPieChart();
}

// 加载支付方式数据（饼图）
void SalesAnalysis::loadPaymentData()
{
    if (!m_salesAnalysisDAO) return;

    QDate startDate = m_startDateEdit->date();
    QDate endDate = m_endDateEdit->date();

    m_paymentData = m_salesAnalysisDAO->getPaymentMethodData(startDate, endDate);
    updatePaymentPieChart();
}

// 更新柱状图数据及样式
void SalesAnalysis::updateBarChart()
{
    if (!m_barSeries || !m_salesAmountSet || !m_grossProfitSet || !m_axisX || !m_axisY) {
        qDebug() << "updateBarChart: 图表组件未初始化";
        return;
    }

    qDebug() << "updateBarChart: 开始更新图表，数据条数:" << m_chartData.size()
             << "显示销售额:" << m_showSalesAmount << "显示毛利润:" << m_showGrossProfit;

    // 设置数据集属性
    m_salesAmountSet->setLabel(tr("销售额"));
    m_salesAmountSet->setColor(QColor("#3498db"));
    m_grossProfitSet->setLabel(tr("毛利润"));
    m_grossProfitSet->setColor(QColor("#2ecc71"));

    // 清空现有数据
    if (m_salesAmountSet->count() > 0) {
        m_salesAmountSet->remove(0, m_salesAmountSet->count());
    }
    if (m_grossProfitSet->count() > 0) {
        m_grossProfitSet->remove(0, m_grossProfitSet->count());
    }

    QStringList categories;
    double maxValue = 0;

    // 添加数据并计算最大值
    if (!m_chartData.isEmpty()) {
        for (int i = 0; i < m_chartData.size(); ++i) {
            const auto &record = m_chartData[i];
            QString timePeriod = record["time_period"].toString();
            double salesAmount = record["sales_amount"].toDouble();
            double grossProfit = record["gross_profit"].toDouble();

            categories << timePeriod;
            m_salesAmountSet->append(salesAmount);
            m_grossProfitSet->append(grossProfit);

            if (m_showSalesAmount) {
                maxValue = qMax(maxValue, salesAmount);
            }
            if (m_showGrossProfit) {
                maxValue = qMax(maxValue, grossProfit);
            }
        }
    } else {
        categories << tr("暂无数据");
        m_salesAmountSet->append(0);
        m_grossProfitSet->append(0);
    }

    // 更新坐标轴
    m_axisX->setCategories(categories);
    m_axisY->setRange(0, maxValue > 0 ? maxValue * 1.1 : 100);

    // 同步数据集显示状态
    bool salesAmountInSeries = m_barSeries->barSets().contains(m_salesAmountSet);
    bool grossProfitInSeries = m_barSeries->barSets().contains(m_grossProfitSet);

    if (m_showSalesAmount && !salesAmountInSeries) {
        m_barSeries->append(m_salesAmountSet);
    } else if (!m_showSalesAmount && salesAmountInSeries) {
        m_barSeries->remove(m_salesAmountSet);
    }

    if (m_showGrossProfit && !grossProfitInSeries) {
        m_barSeries->append(m_grossProfitSet);
    } else if (!m_showGrossProfit && grossProfitInSeries) {
        m_barSeries->remove(m_grossProfitSet);
    }

    // 强制刷新图表
    if (m_chart) {
        m_chart->update();
    }

    qDebug() << "updateBarChart: 图表更新完成";
}

// 更新Y轴范围（根据当前显示数据的最大值）
void SalesAnalysis::updateAxisRange()
{
    if (!m_axisY || !m_salesAmountSet || !m_grossProfitSet) {
        return;
    }

    double maxValue = 0;

    if (m_showSalesAmount && m_salesAmountSet->count() > 0) {
        for (int i = 0; i < m_salesAmountSet->count(); ++i) {
            maxValue = qMax(maxValue, m_salesAmountSet->at(i));
        }
    }

    if (m_showGrossProfit && m_grossProfitSet->count() > 0) {
        for (int i = 0; i < m_grossProfitSet->count(); ++i) {
            maxValue = qMax(maxValue, m_grossProfitSet->at(i));
        }
    }

    m_axisY->setRange(0, maxValue > 0 ? maxValue * 1.1 : 100);

    qDebug() << "updateAxisRange: 更新Y轴范围为:" << (maxValue > 0 ? maxValue * 1.1 : 100);
}

// 更新分类销售饼图
void SalesAnalysis::updateCategoryPieChart()
{
    if (!m_categorySeries || m_categoryData.isEmpty()) return;

    m_categorySeries->clear();

    // 计算总销售额
    double totalSales = 0;
    for (const auto &record : m_categoryData) {
        totalSales += record["sales_amount"].toDouble();
    }

    // 添加数据切片
    for (const auto &record : m_categoryData) {
        QString categoryName = record["category_name"].toString();
        double salesAmount = record["sales_amount"].toDouble();
        double percentage = (salesAmount / totalSales) * 100;

        QPieSlice *slice = m_categorySeries->append(categoryName, salesAmount);
        slice->setLabelVisible(true);

        // 设置切片颜色（循环使用预设颜色列表）
        static QList<QColor> colors = {
            QColor(76, 175, 80),   // 绿色
            QColor(33, 150, 243),  // 蓝色
            QColor(255, 193, 7),   // 黄色
            QColor(233, 30, 99),   // 粉色
            QColor(156, 39, 176),  // 紫色
            QColor(255, 87, 34)    // 橙色
        };

        int colorIndex = m_categorySeries->slices().indexOf(slice) % colors.size();
        slice->setBrush(colors[colorIndex]);
    }
}

// 更新导购销售饼图
void SalesAnalysis::updateStaffPieChart()
{
    if (!m_staffSeries || m_staffData.isEmpty()) return;

    m_staffSeries->clear();

    double totalSales = 0;
    for (const auto &record : m_staffData) {
        totalSales += record["sales_amount"].toDouble();
    }

    for (const auto &record : m_staffData) {
        QString staffName = record["staff_name"].toString();
        double salesAmount = record["sales_amount"].toDouble();

        QPieSlice *slice = m_staffSeries->append(staffName, salesAmount);
        slice->setLabelVisible(true);

        static QList<QColor> colors = {
            QColor(76, 175, 80), QColor(33, 150, 243), QColor(255, 193, 7),
            QColor(233, 30, 99), QColor(156, 39, 176), QColor(255, 87, 34)
        };

        int colorIndex = m_staffSeries->slices().indexOf(slice) % colors.size();
        slice->setBrush(colors[colorIndex]);
    }
}

// 更新支付方式饼图
void SalesAnalysis::updatePaymentPieChart()
{
    if (!m_paymentSeries || m_paymentData.isEmpty()) return;

    m_paymentSeries->clear();

    double totalAmount = 0;
    for (const auto &record : m_paymentData) {
        totalAmount += record["total_amount"].toDouble();
    }

    for (const auto &record : m_paymentData) {
        QString paymentMethod = record["payment_method"].toString();
        double amount = record["total_amount"].toDouble();

        QPieSlice *slice = m_paymentSeries->append(paymentMethod, amount);
        slice->setLabelVisible(true);

        static QList<QColor> colors = {
            QColor(76, 175, 80), QColor(33, 150, 243), QColor(255, 193, 7),
            QColor(233, 30, 99), QColor(156, 39, 176), QColor(255, 87, 34)
        };

        int colorIndex = m_paymentSeries->slices().indexOf(slice) % colors.size();
        slice->setBrush(colors[colorIndex]);
    }
}
